#include "os/os.h"
#include "os_util.h"
#include "rtk.h"

os_state os_mutex_create(os_mutex_t *mutex)
{
    if (rtk_mutex_create((rtk_mutex_t *)mutex, "Mutex") == RTK_OK)
        return OS_OK;
    else
        return OS_FAIL;
}

os_state os_mutex_delete(os_mutex_t *mutex)
{
    if (rtk_mutex_delete((rtk_mutex_t *)mutex) == RTK_OK)
        return OS_OK;
    else
        return OS_FAIL;
}

os_state os_mutex_lock(os_mutex_t *mutex, os_time_t wait_ms)
{
    if (rtk_mutex_lock((rtk_mutex_t *)mutex, rtk_msec_to_ticks(wait_ms)) == RTK_OK)
        return OS_OK;
    else
        return OS_FAIL;
}

os_state os_mutex_unlock(os_mutex_t *mutex)
{
    if (rtk_mutex_unlock((rtk_mutex_t *)mutex) == RTK_OK)
        return OS_OK;
    else
        return OS_FAIL;
}

os_thread_handle_t os_mutex_get_holder(os_mutex_t *mutex)
{
    if (rtk_mutex_is_valid((rtk_mutex_t *)mutex) == false)
    {
        return OS_INVALID_HANDLE;
    }

    return (os_thread_handle_t)rtk_mutex_get_holder((rtk_mutex_t *)mutex)->hdl;
}

bool os_mutex_is_valid(os_mutex_t *mutex)
{
    return rtk_mutex_is_valid((rtk_mutex_t *)mutex);
}
